package codegen

import (
	"fmt"
	"gitee.com/hxchjm/goge/codegen/utils"
	"gitee.com/hxchjm/goge/codegen/utils/pathx"
	"github.com/siddontang/go/config"
	"strings"
)

const daoTemplate = `package dao

import (
	"context"
	"time"

	"go-main/library/cache/redis"
	"go-main/library/conf"
	"go-main/library/database/sql"
	"go-main/library/sync/pipeline/fanout"
	xtime "go-main/library/time"
)


// Dao dao interface
type Dao interface {
	Close()
	Ping(ctx context.Context) (err error)
}

// dao dao.
type dao struct {
	db         *sql.DB
	redis      *redis.Redis
	cache      *fanout.Fanout
	demoExpire int32
}

// New a dao and return.
func New(r *redis.Redis, db *sql.DB) (d Dao, cf func(), err error) {
	return newDao(r, db)
}
func newDao(r *redis.Redis, db *sql.DB) (d *dao, cf func(), err error) {
	var cfg struct {
		DemoExpire xtime.Duration
	}
	if err = conf.Bind("app", &cfg); err != nil {
		return
	}
	d = &dao{
		db:         db,
		redis:      r,
		cache:      fanout.New("cache"),
		demoExpire: int32(time.Duration(cfg.DemoExpire) / time.Second),
	}
	cf = d.Close
	return
}

// Close close the resource.
func (d *dao) Close() {
	_ = d.cache.Close()
}

// Ping ping the resource.
func (d *dao) Ping(_ context.Context) (err error) {
	return nil
}
`

func genDao(dir, rootPkg string, cfg *config.Config, filename string) error {
	//name := strings.ToLower(api.Service.Name)
	//filename, err := format.FileNamingFormat(cfg.NamingFormat, name)
	//if err != nil {
	//	return err
	//}

	/*	filename := name
		configName := filename
		if strings.HasSuffix(filename, "-api") {
			filename = strings.ReplaceAll(filename, "-api", "")
		}*/

	return utils.GenFile(utils.FileGenConfig{
		Dir:          dir,
		Subdir:       daoDir,
		Filename:     filename,
		TemplateName: "mainTemplate",
		//Category:        category,
		//TemplateFile:    mainTemplateFile,
		BuiltinTemplate: daoTemplate,
		Data: map[string]string{
			"importPackages": genDaoImports(rootPkg),
			"serviceName":    rootPkg,
		},
	})
}

func genDaoImports(parentPkg string) string {
	var imports []string
	imports = append(imports, fmt.Sprintf("\"%s\"", pathx.JoinPackages(parentPkg, appDir)))
	//imports = append(imports, fmt.Sprintf("\"%s/core/conf\"", vars.ProjectOpenSourceURL))
	//imports = append(imports, fmt.Sprintf("\"%s/rest\"", vars.ProjectOpenSourceURL))
	return strings.Join(imports, "\n\t")
}
